<?php
namespace Modules\Product\Http\Controllers\Admin\V1;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use Modules\Product\Entities\Product;
use Modules\Product\Entities\Sku;

use Validator;
use ThrowException;
use DB;

class SkuController extends Controller
{
    public function index(Request $req)
    {
        $rule = [
            'product_id' => ['required']
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $options = $req->all();

        $options['where']['product_id'] = $req->product_id;

        $options['only'] = [
            'id',
            'uuid',
            'number',
            'attrs',
            'thumb',
            'money_price',
            'score_price',
            'stock',
            'weight',
            'cover_chip_status',
            'cover_chip_id',
            'cover_chip_total',
            'cover_chip_count',
            'sales',
            'status'
        ];

        $list = Sku::getList($options);

        return $list->generateListResponse();
    }

    public function update(Request $req, $uuid)
    {
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $item = Sku::getEntity([
            'uuid' => $uuid
        ]);

        if ($req->type === 'update') {
            $info = $req->input('attributes');
            $item->update($info);
        }

        return [];
    }

    public function batch(Request $req)
    {
        DB::beginTransaction();

        if ($req->type === 'update') {
            $list = $req->list;
            $item = null;

            foreach ($list as $sku) {
                $item = Sku::getEntity([
                    'id' => $sku['id']
                ]);

                $item->update($sku);
            }

            // 更新父级商品的销量和库存
            $item->product->updateSalesAndStock();
        }

        DB::commit();

        return [];
    }
}
